/**
 * %%
 * %%
 */
package com.leehom.arch.obs.metrics.exporter;

import java.util.HashMap;
import java.util.Map;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricRegistry.MetricSupplier;

/**
 * @类名: MetricHolder
 * @说明: metric持有容器，全局获取/创建metric
 *
 * @author   leehom
 * @Date	 2021年12月3日 下午2:03:59
 * 修改记录：
 *
 * @see 	 
 */
public class MetricHolder {

	/** metric注册器*/
	private MetricRegistry registry;
	
	public void init() {
		
	}
	
	// group.tag..., group分组统计；tag，维度，TagExtractor解释
	public Counter getOrCreateCounter(String group, String... tags) {
		Counter counter = registry.counter(MetricRegistry.name(group, tags));
		return counter;
	}
	
	@SuppressWarnings({"rawtypes", "unchecked" })
	public <T> Gauge<T> addGauge(String group, MetricSupplier<Gauge> supplier, String... tags) {
		Gauge<T> gauge = registry.gauge(key(group, tags), supplier);
		return gauge;
	}
	
	private String key(String group, String... tags) {
		final StringBuilder builder = new StringBuilder();
        append(builder, group);
        if (tags != null) {
            for (String tag : tags) {
                append(builder, tag);
            }
        }
        return builder.toString();
	}
	
    private static void append(StringBuilder builder, String part) {
        if (part != null && !part.isEmpty()) {
            if (builder.length() > 0) {
                builder.append('.');
            }
            builder.append(part);
        }
    }


	public void setRegistry(MetricRegistry registry) {
		this.registry = registry;
	}
}
